package com.jdd.modules.people.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.common.util.ResultGenerator;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.dao.entity.TDepartment;
import com.jdd.dao.service.TDepartmentService;
import com.jdd.dao.service.TProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @className Department
 * @author: zxl
 * @describe: 部门组织表
 * @date: 2022/9/22/19:29
 * @vision: 1.0
 */
@Slf4j
@Api("部门组织表")
@RestController("Department")
@RequestMapping("/department")
public class DepartmentController {
    @Resource
    private TDepartmentService tDepartmentService;

    @Resource
    private TProjectService tProjectService;

    @ApiOperation(value = "查询部门组织表", notes = "查询部门组织表")
    @AutoLog("部门组织表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<TDepartment>> list(TDepartment tDepartment,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        Result<IPage<TDepartment>> result = new Result<>();
        List<String> projectCodes = LoginUserUtils.getLoginUser().getProjectCodes();
        if (projectCodes.size()<=0){
            return result;
        }
        QueryWrapper<TDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("project_id",projectCodes);
        if (tDepartment.getProjectId()!=null){
            queryWrapper.eq("project_id",tDepartment.getProjectId());
        }
        if (tDepartment.getId()!=null){
            queryWrapper.eq("id",tDepartment.getId());
        }

        Page<TDepartment> page = new Page(pageNo, pageSize);
        IPage<TDepartment> tDepartmentIPage = tDepartmentService.page(page, queryWrapper);
        for (TDepartment record : tDepartmentIPage.getRecords()) {
            if (record.getProjectId() != null && !record.getProjectId().equals("")) {
                String projectName = tProjectService.getById(record.getProjectId()).getName();
                if (projectName != null) {
                    record.setProjectName(projectName);
                }
            }
            if (record.getParentId()!=null){
                QueryWrapper<TDepartment> departmentQueryWrapper = new QueryWrapper<>();
                departmentQueryWrapper.eq("id",record.getParentId());
                TDepartment department = tDepartmentService.getOne(departmentQueryWrapper);
                if (department!=null){
                    record.setParentName(department.getName());
                }

            }
        }
        result.setResult(tDepartmentIPage);
        result.setSuccess(true);
        return result;
    }

    @AutoLog("部门组织表删除")
    @ApiOperation(value = "部门组织表删除", notes = "部门组织表删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            int count =tDepartmentService.count(new QueryWrapper<TDepartment>().eq("parent_id",id));
        if(count>0){
            return ResultGenerator.genFailResult("该部门已绑定其他子部门，请先删除子部门");
        }
            tDepartmentService.removeById(id);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除失败");
        }
        return ResultGenerator.genSuccessResult("删除成功");
    }



    @AutoLog("部门组织批量删除")
    @ApiOperation(value = "部门组织表批量删除", notes = "部门组织表批量删除")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids",required = true) String ids){
        List<String> keys = Arrays.asList(ids.split(","));
        List<String> bandIds = new ArrayList<>();
        for (String key : keys) {
            TDepartment tDepartment = tDepartmentService.getOne(new QueryWrapper<TDepartment>().eq("parent_id",key));
            if (tDepartment!=null){
                bandIds.add(tDepartment.getId());
            }
        }
        if (bandIds.size()!=0){
            int a ;
            for ( a=0;a<bandIds.size();a++) {
                if ( keys.contains(bandIds.get(a))){
                   bandIds.remove(a);
                }
            }
            if (bandIds.size()!=0){
                return ResultGenerator.genFailResult("该部门已绑定其他子部门，请先删除子部门");
            }
        }
        try {
            tDepartmentService.removeByIds(keys);
        }catch (Exception e){
          return ResultGenerator.genFailResult("删除失败"+e);
        }
        return ResultGenerator.genSuccessResult("删除成功");

        }

    @AutoLog("部门组织添加")
    @ApiOperation(value = "部门组织表添加", notes = "部门组织表添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody TDepartment tDepartment){
        Result result = new Result();
        tDepartment.setId(SnowFlakeUtil.getId());
        tDepartmentService.save(tDepartment);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public Result<?> edit(@RequestBody TDepartment tDepartment){
        tDepartmentService.saveOrUpdate(tDepartment);
        return ResultGenerator.genSuccessResult("修改成功");
    }

    @GetMapping(value = "/getDepartInfo")
    public Result<List<TDepartment>> getDepartInfo(@RequestParam(name = "projectId") String projectId){
        Result<List<TDepartment>> result = new Result<>();
        LambdaQueryWrapper<TDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TDepartment::getProjectId,projectId);
        List<TDepartment> list = tDepartmentService.list(queryWrapper);
        result.setResult(list);
        result.setSuccess(true);
        return result;
    }
}


